# -*- coding:utf-8 -*-
# @Time:2024/4/1921:01
# @Author:miuzg
# @FileName:new test2.py
# @Software:PyCharm
import re
import js2py
import time
import requests
from urllib.parse import quote # 字符转码

# r_toke = '962ffa192e64ad11e3ea9400e2df75c1'
# u = 1740982334662
# s = '12574478'
# n_data = '{"params":"{\\"bizId\\":\\"443\\",\\"resId\\":\\"36500751\\",\\"bizCode\\":\\"search\\"}"}'


class TaobaoSpider:
    def __init__(self):
        self.start_url = 'https://h5api.m.taobao.com/h5/mtop.relationrecommend.wirelessrecommend.recommend/2.0/'
        self.headers = {
            'Referer': 'https://uland.taobao.com/sem/tbsearch?clk1=26f84c5139c34dfc6687de39804f7568&keyword=%E5%A5%B3%E8%A3%85&localImgKey=&msclkid=884b6a063f2d1e022c9c0dc37a5982c9&page=1&q=%E5%A5%B3%E8%A3%85&refpid=mm_2898300158_3078300397_115665800437&tab=all&upsId=26f84c5139c34dfc6687de39804f7568',
            'cookie': 'cna=mgBDIMR97xABASABDailoIQ9; thw=xx; t=0279f69274428768e60c606f9c566301; xlly_s=1; 3PcFlag=1740900151681; cookie2=1aebaeae93b1cef108f3e0e8aeb69720; _tb_token_=e458b97b4711; mtop_partitioned_detect=1; _m_h5_tk=962ffa192e64ad11e3ea9400e2df75c1_1740989185851; _m_h5_tk_enc=0c14e72279fd6e11b0b7316b722b952f; tfstk=gKmS3hVPV_f5saOnobv4hwA66hZQFK-wF9wKIvIPpuERvpGEgDzLTUcQRXl0J0rrUjNK_jNRYeVPAkMItXlIKL2L9XhQT482bYDuxkdaOh-ZE05qTN3QJ8Qvp82w38QNBfT0xkdwgZSLrhZnsqDnmvQYHS2QpJIK9reYLSeReghLMreTQ_EK9kpbMRwG96ILpxeYESFLvzUJhxF0dke-go-b3pPSFLLzdOJDI1H7GMIKc-d30YT5x-nYFzNtemjdvp27P5H8GCcnu5UxKyihKMateVc3BbCJOWmjH03t6I7zwVwIQ2MJ2iErqY3TJcdhJfZSOPn8l9ItEYFzc-n9LNVqc7lKVrpNfyrxbPE-uEAz8uws90c5dMht3AouoDO1MW0zIoeIxdQQOyIz5GP6yaQChPjQh5JXhwbn01QIpqHloTz8n-5whK17Dze0h-nehweQy-22IK9fNo5..; isg=BIGB781xghXFFe5YQRqclplxkM2brvWgSfl14uPXyQjmyqCcAf8FcPmMrD6MRI3Y',
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0'
        }
        self.temp_time = str(int(time.time() * 1000))
        # 载荷里获取数据
        self.data = [{"appId": "43356",
                      "params": "{\"device\":\"HMA-AL00\",\"isBeta\":\"false\",\"grayHair\":\"false\",\"from\":\"nt_history\",\"brand\":\"HUAWEI\",\"info\":\"wifi\",\"index\":\"4\",\"rainbow\":\"\",\"schemaType\":\"auction\",\"elderHome\":\"false\",\"isEnterSrpSearch\":\"true\",\"newSearch\":\"false\",\"network\":\"wifi\",\"subtype\":\"\",\"hasPreposeFilter\":\"false\",\"prepositionVersion\":\"v2\",\"client_os\":\"Android\",\"gpsEnabled\":\"false\",\"searchDoorFrom\":\"srp\",\"debug_rerankNewOpenCard\":\"false\",\"homePageVersion\":\"v7\",\"searchElderHomeOpen\":\"false\",\"search_action\":\"initiative\",\"sugg\":\"_4_1\",\"sversion\":\"13.6\",\"style\":\"list\",\"ttid\":\"600000@taobao_pc_10.7.0\",\"needTabs\":\"true\",\"areaCode\":\"CN\",\"vm\":\"nw\",\"countryNum\":\"156\",\"m\":\"pc_sem\",\"page\":1,\"n\":48,\"q\":\"%E7%AC%94%E8%AE%B0%E6%9C%AC%E7%94%B5%E8%84%91\",\"qSource\":\"manual\",\"pageSource\":\"\",\"tab\":\"all\",\"pageSize\":48,\"totalPage\":100,\"totalResults\":4800,\"sourceS\":\"0\",\"sort\":\"_coefp\",\"bcoffset\":\"\",\"ntoffset\":\"\",\"filterTag\":\"\",\"service\":\"\",\"prop\":\"\",\"loc\":\"\",\"start_price\":null,\"end_price\":null,\"startPrice\":null,\"endPrice\":null,\"itemIds\":null,\"p4pIds\":null,\"categoryp\":\"\",\"myCNA\":\"mgBDIMR97xABASABDailoIQ9\",\"clk1\":\"26f84c5139c34dfc6687de39804f7568\",\"refpid\":\"mm_2898300158_3078300397_115665800437\"}"}]
    def get_sign(self):
        # 获取token值
        token = re.findall('_m_h5_tk=(/*?)',self.headers['cookie'])
        sign_str = f'{token}&{self.temp_time}&12574478&{self.data}'

        with open('tb.js','r') as f:
            js_code = f.read()
        js = js2py.EvalJs()
        js.execute(js_code)

        # 把文本放到js里去处理得到一个加密后的sign
        return js.c(sign_str)


    def run(self):
        # 获取到了签名
        sign = self.get_sign()
        print(sign)

        # 请求参数
        params = f'?jsv=2.7.2&appKey=12574478&t=1740982983595&sign=225b20455336c8a981eafc9956b32985&api=mtop.relationrecommend.wirelessrecommend.recommend&v=2.0&type=jsonp&dataType=jsonp&callback=mtopjsonp9&data='

        url = self.start_url + params + quote(f'{self.data}')

        # 发送请求
        res = requests.get(url,headers=self.headers)
        print(res)
        print(res.text)

        # 会获取到json数据

if __name__ == '__main__':
    spider = TaobaoSpider()
    spider.run()
